package com.teapos.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import com.teapos.annotation.DataSource;
import com.teapos.util.ThreadLocalUtil;

/**
 * 动态数据源切面
 * @author kangrui
 *
 */
@SuppressWarnings("rawtypes")
@Component
@Aspect
public class DataSourceAspect {
	
	@Pointcut("execution(* com.teapos.dao.*.*(..))")
	public void pointcut(){}
	
	@Around("pointcut()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		//System.err.println("进入切面");
		String methodName = pjp.getSignature().getName();
        Class[] clazzs = ((MethodSignature)pjp.getSignature()).getMethod().getParameterTypes();
        Method method = pjp.getTarget().getClass().getMethod(methodName, clazzs);
        DataSource c_a = AnnotationUtils.findAnnotation(pjp.getTarget().getClass(), DataSource.class);
        DataSource m_a = AnnotationUtils.findAnnotation(method, DataSource.class);
        if(m_a!=null) {
        	//System.err.println("方法上有动态数据员注解："+m_a.value());
    		ThreadLocalUtil.put("datasource", m_a.value());
    	} else if(c_a!=null&&m_a==null){
    		//System.err.println("类上有动态数据员注解："+c_a.value());
    		ThreadLocalUtil.put("datasource", c_a.value());
    		System.err.println(c_a.value());
    	}
        Object result = null;
        try {
        	result = pjp.proceed();
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			ThreadLocalUtil.remove();
		}
		return result;
	}

}
